<template>
  <el-form>
    <el-form-item label="用户头像">
      <crop-upload
        :is-show="show"
        :action="action"
        :data="data"
        @onUpload="onUpload"
        @onShow="onShow"
      />
      <span class="avatar" @click="beforeAvatarUpload">
        <el-avatar
          icon="el-icon-user-solid"
          :size="80"
          :src="form.avatar"
          style="margin-top:10px;"
        />
      </span>
    </el-form-item>
    <el-form-item label="用户名">
      <el-input v-model.trim="form.nickname" placeholder="用户名" />
    </el-form-item>
    <el-form-item label="密码">
      <el-input v-model.trim="form.password" placeholder="请输入密码(不填则不修改)" />
    </el-form-item>
    <el-form-item v-if="form.password" label="确认密码">
      <el-input v-model.trim="form.password1" placeholder="请输入确认密码" />
    </el-form-item>
    <el-form-item label="用户名">
      <el-input v-model.trim="form.nickname" placeholder="邮箱" />
    </el-form-item>
    <el-form-item label="介绍">
      <el-input
        v-model.trim="form.information"
        type="textarea"
        :rows="4"
        placeholder="介绍"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">更新</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getToken } from '@/api/qiniu'
import { save } from '@/api/admin'
import CropUpload from '@/components/CropUpload'

export default {
  components: {
    CropUpload
  },
  props: {
    user: {
      type: Object,
      default() {
        return {
          nickname: '',
          information: '',
          avatar: ''
        }
      }
    }
  },
  data() {
    return {
      data: {
        token: ''
      },
      action: '',
      form: {
        id: 0,
        nickname: '',
        information: '',
        avatar: '',
        password: ''
      },
      imageUrl: '',
      show: false
    }
  },
  created() {
    this.form.nickname = this.user.nickname
    this.form.information = this.user.information
    this.form.avatar = this.user.avatar
    this.form.id = this.user.id
  },
  methods: {
    submit() {
      this.$store.commit('app/SHOW_LOADING')
      save(this.form).then(({ status, data }) => {
        this.$store.commit('app/HIDE_LOADING')
        if (status) {
          this.$store.dispatch('user/getInfo')
          this.$message({
            message: '管理员信息更新成功',
            type: 'success',
            duration: 2e3
          })
        }
      })
    },
    onUpload({ status, data }) {
      const { url } = data
      this.form.avatar = url
    },
    onShow(show) {
      this.show = show
    },
    async beforeAvatarUpload() {
      const { status, token, upload } = await getToken({
        type: 2
      })
      if (status) {
        this.action = upload
        this.data.token = token
        this.show = true
      }
    }
  }
}
</script>
<style lang="scss">
.avatar {
  display: block;
  cursor: pointer;
  float: left;
}
</style>
